package com.delianna.bwt.helpers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;

public class Translator {

	private Lang language;
	private HashMap<String, Phrase> phrases;
	private Context context;

	public static enum Lang {
		en, es, fr;
	}

	public Translator(Context ctx) {
		context = ctx;
		Resources res = context.getResources();
		android.content.res.Configuration conf = res.getConfiguration();
		language = Lang.valueOf(conf.locale.getLanguage().toLowerCase());
		loadPhrases();
	}

	public Lang getLanguage() {
		return language;
	}
	
	public String Translate(String key){
		if (key == null) return "";
		Phrase p = phrases.get(key.toLowerCase());
		if (p != null)
			return p.Translate(language);
		else
			return key;
	}
	
	public String TranslateByWord(String sentence){
		sentence = sentence.trim();
		String words[] = sentence.split(" ");
		String retVal = "";
		if (words != null){
			for(String w: words){
				retVal += Translate(w) + " ";
			}
			return retVal.trim();
		}
		return sentence;
	}

	private void loadPhrases() {
		InputStream is = context.getResources().openRawResource(
				com.delianna.bwt.R.raw.translate);
		InputStreamReader inputStreamReader = new InputStreamReader(is);
		BufferedReader reader = new BufferedReader(inputStreamReader);
		String line;
		String elems[];
		Phrase p;
		phrases = new HashMap<String, Phrase>();
		try {
			while ((line = reader.readLine()) != null) {
				elems = line.split(",");
				p = new Phrase(elems[1], elems[2], elems[3]);
				phrases.put(elems[0], p);
			}
		} catch (IOException e) {
			Log.w("TRANSLATOR", "Failed to load Resource to translate");
		}
	}

	class Phrase {
		public String en;
		public String es;
		public String fr;

		public Phrase(String english, String spanish, String french) {
			en = english;
			es = spanish;
			fr = french;
		}

		public String Translate(Lang language) {
			switch (language) {
			case en:
				return en;
			case es:
				return es;
			case fr:
				return fr;
			default:
				return en;
			}
		}
	}
}
